package com.hyjx.framework.common;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 异常统一处理类
 *
 * @author Peter
 */
public class HyjxExceptionHandler implements HandlerExceptionResolver {
    
    /**
     * 捕获到异常后的处理及跳转
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @return
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                         Exception ex) {
        String reqType = request.getHeader("x-requested-with");
        if ("XMLHttpRequest".equals(reqType)) {
            //ajax request
            String msg = ex.getMessage();
            try {
                if (StringUtils.isNotEmpty(msg)) {
                    response.getWriter().write(msg);
                    System.err.println(msg);
                } else {
                    if (ex != null)
                        ex.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return new ModelAndView();
        }
        
        ModelAndView mav = new ModelAndView("/framework/common/errors/500");
        mav.addObject("exMessage", ex.getMessage());
        
        ByteArrayOutputStream buf = new java.io.ByteArrayOutputStream();
        ex.printStackTrace(new java.io.PrintWriter(buf, true));
        String exMessageDetail = buf.toString();
        //System.err.println(exMessageDetail);
        ex.printStackTrace();
        try {
            buf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mav.addObject("exMessageDetail", exMessageDetail);
        
        return mav;
    }
}